<?php

namespace MoChat\Salesman\Action;

use Hyperf\DbConnection\Db;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 个人中心统计
 * @Controller
 */
class MyData extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/my/data", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        $workEmployeeId = $user['workEmployeeId'];

        //TODO 个人中心统计
        return [
            'clientNumber' => Db::table('client')->where('work_employee_id',$workEmployeeId)->count(),//客户数
            'signNumber' => Db::table('clock_record')->where('work_employee_id',$workEmployeeId)->count(),//总签到数
            'followUp' => Db::table('client as client')
                ->leftJoin('client_follow_record as record','record.client_id','=','client.id')
                ->whereRaw('mc_record.created_at is null or mc_record.created_at < ?',[date('Y-m-d H:i:s',strtotime('-30 day'))])
                ->groupBy(['client.id'])
                ->count()//30天未跟进数
        ];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
